package com.powerteam.service.crm.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.powerteam.exception.BusinessException;
import com.powerteam.mapper.crm.ContactsMapper;
import com.powerteam.mapper.crm.CustomerMapper;
import com.powerteam.model.crm.*;
import com.powerteam.service.crm.ActivityService;
import com.powerteam.service.crm.CustomerService;
import com.powerteam.service.crm.ShareGroupService;
import com.powerteam.vo.Result;
import com.powerteam.vo.crm.QueryCustomerVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.powerteam.model.enums.ActivityTypeEnum.ACTIVITY_TYPE_SYSTEM_TRACE;
import static com.powerteam.model.enums.ResourceTypeEnum.RESOURCE_TYPE_CUSTOMER;

/**
 * 客户相关服务接口实现
 *
 * @author jinming.zhang
 * @version 0.0.1
 * @date 2021/12/30
 */
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    private static final String CLASS_NAME = "CustomerServiceImpl";

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private ShareGroupService shareGroupService;

    @Autowired
    private ActivityService activityService;

    @Override
    public PageInfo<Customer> find(QueryCustomerVO vo) {

        try {

            // 如果没有禁用分页 设置分页信息
            if (StringUtils.isEmpty(vo.getDisablePaging()) || !vo.getDisablePaging()) {
                PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            }
            // 分页查询客户信息
            vo.setWord(StringUtils.isEmpty(vo.getWord()) ? null : "%".concat(vo.getWord()).concat("%"));
            List<Customer> customerList = customerMapper.find(vo);
            log.info("{} find 分页查询客户信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(vo), JSON.toJSON(customerList));

            return new PageInfo<>(customerList);
        } catch (Exception e) {
            log.warn("{} find 分页查询客户信息异常 入参0:{}", CLASS_NAME, JSON.toJSON(vo));
            log.error(e.getMessage(), e);
            return new PageInfo<>(new ArrayList<>());
        }
    }

    @Override
    public List<CustomerCategory> findAllCustomerCategory() {

        try {
            List<CustomerCategory> allCustomerCategory = customerMapper.findAllCustomerCategory();
            log.info("{} findAllCustomerCategory 查找所有客户类别 结果0:{}", CLASS_NAME, JSON.toJSON(allCustomerCategory));

            return allCustomerCategory;
        } catch (Exception e) {
            log.warn("{} findAllCustomerCategory 查找所有客户类别异常", CLASS_NAME);
            log.error(e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Industry> findAllIndustry() {

        try {

            List<Industry> allIndustry = customerMapper.findAllIndustry();
            log.info("{} findAllIndustry 查找所有行业 结果0:{}", CLASS_NAME, JSON.toJSON(allIndustry));

            return allIndustry;
        } catch (Exception e) {
            log.warn("{} findAllIndustry 查找所有行业异常", CLASS_NAME);
            log.error(e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Source> findAllSource() {
        try {

            List<Source> allSource = customerMapper.findAllSource();
            log.info("{} findAllSource 查找所有来源 结果0:{}", CLASS_NAME, JSON.toJSON(allSource));

            return allSource;
        } catch (Exception e) {
            log.warn("{} findAllSource 查找所有来源异常", CLASS_NAME);
            log.error(e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = {BusinessException.class}, propagation = Propagation.REQUIRED)
    public Result insert(Customer customer) {

        try {
            customer.setCreateDate(new Date());
            customer.setOwner(customer.getCreateBy());
            Result result = new Result();

            if (!this.checkCustomerName(customer).isSuccess()) {
                result.setMessage("客户名称重复");
                return result;
            }

            if (customerMapper.insert(customer) > 0) {
                log.info("{} insert 添加客户信息 入参0:{}", CLASS_NAME, customer);

                ShareGroup shareGroup = new ShareGroup();
                shareGroup.setResourceType(RESOURCE_TYPE_CUSTOMER.getCode());
                shareGroup.setResourceId(customer.getCustomerId());
                shareGroup.setUserId(customer.getCreateBy());

                if (shareGroupService.insert(shareGroup).isSuccess()) {
                    log.info("{} insert 添加共享信息 入参0:{}", CLASS_NAME, shareGroup);

                    Activity activity = new Activity();
                    activity.setResourceType(RESOURCE_TYPE_CUSTOMER.getCode());
                    activity.setResourceId(customer.getCustomerId());
                    activity.setActivityType(ACTIVITY_TYPE_SYSTEM_TRACE.getCode());
                    activity.setContent("创建了客户");
                    activity.setCreateDate(new Date());
                    activity.setCreateBy(customer.getCreateBy());

                    if (activityService.insert(activity).isSuccess()) {
                        log.info("{} insert 添加动态信息 入参0:{}", CLASS_NAME, activity);
                        result.setSuccess(true);
                        return result;
                    } else {
                        throw new BusinessException("添加动态失败");
                    }
                } else {
                    throw new BusinessException("添加共享组失败");
                }
            } else {
                throw new BusinessException("添加客户失败");
            }
        } catch (BusinessException e) {
            log.warn("{} insert 添加客户信息异常 入参0:{}", CLASS_NAME, customer);
            log.error(e.getMessage(), e);
            throw new BusinessException("添加客户失败");
        }

    }

    @Override
    public Result checkCustomerName(Customer customer) {

        try {

            Boolean existCustomerName = customerMapper.existCustomerName(customer);
            log.info("{} checkCustomerName 查询客户是否存在 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(customer), existCustomerName);

            // 存在 返回false 不存在 返回true
            return new Result(!existCustomerName);
        } catch (Exception e) {
            log.warn("{} checkCustomerName 查询客户是否存在异常 入参0:{}", CLASS_NAME, JSON.toJSON(customer));
            log.error(e.getMessage(), e);
            return new Result(false);
        }
    }

    @Override
    public Customer findById(Integer customerId) {

        try {

            Customer customer = customerMapper.findById(customerId);
            log.info("{} findById 根据Id查询客户信息 入参0:{} 结果0:{}", CLASS_NAME, customerId, JSON.toJSON(customer));

            return customer;
        } catch (Exception e) {
            log.warn("{} findById 根据Id查询客户信息异常 入参0:{}", CLASS_NAME, customerId);
            log.error(e.getMessage(), e);
            return new Customer();
        }
    }

    @Override
    @Transactional(rollbackFor = {BusinessException.class}, propagation = Propagation.REQUIRED)
    public Result update(Customer customer) {

        try {

            boolean result = customerMapper.update(customer) > 0;
            log.info("{} update 修改客户信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(customer), result);

            return new Result(result);
        } catch (Exception e) {
            log.warn("{} update 修改客户信息异常 入参0:{}", CLASS_NAME, JSON.toJSON(customer));
            log.error(e.getMessage(), e);
            throw new BusinessException("修改客户信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = {BusinessException.class}, propagation = Propagation.REQUIRED)
    public Result updateStar(Customer customer) {

        try {
            // 根据Id查询客户信息
            Customer model = this.findById(customer.getCustomerId());
            if (ObjectUtils.isEmpty(model)) {
                throw new BusinessException("更新星级失败");
            }
            log.info("{} updateStar 根据Id查询客户信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(customer), JSON.toJSON(model));

            model.setStar(customer.getStar());
            boolean result = customerMapper.update(model) > 0;
            log.info("{} updateStar 更新星级信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(model), result);

            return new Result(result);
        } catch (Exception e) {
            log.info("{} updateStar 更新星级信息异常 入参0:{}", CLASS_NAME, JSON.toJSON(customer));
            log.error(e.getMessage(), e);
            throw new BusinessException("更新星级失败");
        }

    }

    @Override
    @Transactional(rollbackFor = {BusinessException.class}, propagation = Propagation.REQUIRED)
    public Result updateLocation(Customer customer) {

        try {

            // 根据Id查询客户信息
            Customer model = this.findById(customer.getCustomerId());
            if (ObjectUtils.isEmpty(model)) {
                throw new BusinessException("更新位置失败");
            }
            log.info("{} updateLocation 根据Id查询客户信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(customer), JSON.toJSON(model));

            model.setLng(customer.getLng());
            model.setLat(customer.getLat());
            boolean result = customerMapper.update(model) > 0;
            log.info("{} updateLocation 更新位置信息 入参0:{} 结果0:{}", CLASS_NAME, JSON.toJSON(model), result);

            return new Result(result);
        } catch (Exception e) {
            log.warn("{} updateLocation 更新位置信息异常 入参0:{}", CLASS_NAME, JSON.toJSON(customer));
            log.error(e.getMessage(), e);
            throw new BusinessException("更新位置失败");
        }
    }

    @Override
    @Transactional(rollbackFor = {BusinessException.class}, propagation = Propagation.REQUIRED)
    public Result remove(Integer customerId) {

        try {

            // 删除客户信息
            boolean result = customerMapper.remove(customerId) > 0;
            log.info("{} update 删除客户信息 入参0:{} 结果0:{}", CLASS_NAME, customerId, result);

            // 删除客户下的所有联系人
            boolean removeAllContacts = contactsMapper.removeAll(customerId) >= 0;
            log.info("{} update 删除客户下的所有联系人信息 入参0:{} 结果0:{}", CLASS_NAME, customerId, removeAllContacts);

            return new Result(removeAllContacts);
        } catch (Exception e) {
            log.warn("{} update 删除客户信息异常 入参0:{}", CLASS_NAME, customerId);
            log.error(e.getMessage(), e);
            throw new BusinessException("删除客户信息错误");
        }
    }
}
